package com.connector.base.utils;

import com.alibaba.fastjson.util.IOUtils;
import com.google.common.base.Charsets;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;

public class MD5Utils
{
    public static String encrypt(final File file) {
        InputStream in = null;
        try {
            final MessageDigest digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            final byte[] buffer = new byte[1024];
            int readLen;
            while ((readLen = in.read(buffer)) != -1) {
                digest.update(buffer, 0, readLen);
            }
            return toHex(digest.digest());
        }
        catch (Exception e) {
            return "";
        }
        finally {
            IOUtils.close((Closeable)in);
        }
    }

    public static String encrypt(final String text) {
        try {
            final MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(text.getBytes(Charsets.UTF_8));
            return toHex(digest.digest());
        }
        catch (Exception e) {
            return "";
        }
    }

    public static String encrypt(final byte[] bytes) {
        try {
            final MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(bytes);
            return toHex(digest.digest());
        }
        catch (Exception e) {
            return "";
        }
    }

    private static String toHex(final byte[] bytes) {
        final StringBuilder buffer = new StringBuilder(bytes.length * 2);
        for (int i = 0; i < bytes.length; ++i) {
            buffer.append(Character.forDigit((bytes[i] & 0xF0) >> 4, 16));
            buffer.append(Character.forDigit(bytes[i] & 0xF, 16));
        }
        return buffer.toString();
    }

    public static String hmacSha1(final String data, final String encryptKey) {
        final String HMAC_SHA1 = "HmacSHA1";
        final SecretKeySpec signingKey = new SecretKeySpec(encryptKey.getBytes(Charsets.UTF_8), "HmacSHA1");
        try {
            final Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(signingKey);
            mac.update(data.getBytes(Charsets.UTF_8));
            return toHex(mac.doFinal());
        }
        catch (Exception e) {
            return "";
        }
    }

    public static String sha1(final String data) {
        try {
            final MessageDigest digest = MessageDigest.getInstance("SHA-1");
            return toHex(digest.digest(data.getBytes(Charsets.UTF_8)));
        }
        catch (Exception e) {
            return "";
        }
    }
}
